import java.util.Calendar;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

/*
 * This class is responsible for handling the feed which provides the jobs to be scheduled. It
 * is responsible for creating the "jobs" and putting the jobs in a jobQueue. This jobQueue then
 * needs to be transferred to the job handler class. 
 */

public class JobFeeder implements IJobFeeder,Runnable
{
	private Queue<IJob> myJobQueue = null;
	protected volatile Boolean running = null;
	protected IJobHandler jobHandler = null;
	
	public JobFeeder(Boolean running)
	{
		myJobQueue = new LinkedList<IJob>();
		this.running = running;
	}
	
	public void run()
	{
		// method called by controlling class to start reading the feed and creating jobs
		System.out.println("Job Feeder started !!");
		
		while(running)
		{
			System.out.println("Creating and sending jobs ...");
			
			createJob();
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.out.println("Exception in job feeder sleeping");
				e.printStackTrace();
			}
		}
		
		System.out.println("Job feeder finished !!");
	}
	
	private void createJob() 
	{
		// method to create jobs and the jobQueue from those jobs.
		
		myJobQueue.clear();
		
		Calendar timeObject = Calendar.getInstance();
		Random randomVariable = new Random();
		int resourceRequirement = randomVariable.nextInt(5);
		int timeRequired = randomVariable.nextInt(300);
		
		IJob newJob = new Job(timeObject.toString(),"This is job " + timeObject.toString(),resourceRequirement,timeRequired);
		myJobQueue.offer(newJob);
		
	}
	
	public Queue<IJob> getJobQueue()
	{
		return myJobQueue;
	}
	
	public void assignJobHandlerObject(IJobHandler jobHandler)
	{
		this.jobHandler = jobHandler;
	}
}
